package com.smmisia.article.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@RestController
public class testController {
    private static final Map<Integer, SseEmitter> emitters = new ConcurrentHashMap<>();

    @PostMapping("/publisher")
    public void publisher(@RequestParam Integer id, @RequestParam String content) {
        SseEmitter sseEmitter = emitters.get(id);
        try {
            sseEmitter.send(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/subscribe")
    public SseEmitter subscribe(@RequestParam Integer id) {
        SseEmitter sseEmitter = emitters.get(id);
        if(sseEmitter == null){
            sseEmitter = new SseEmitter();
            sseEmitter.onCompletion(()->emitters.remove(id));
            sseEmitter.onTimeout(()->emitters.remove(id));
            emitters.put(id,sseEmitter);
        }
        return sseEmitter;
    }
}
